<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2018-03-02 17:14:35 apple $
*/
namespace core;
defined('BY_JYA') or exit('error');
class fans_api{
	public function get_access_token($wechat,$code){
		if(!$wechat['appid'] || !$wechat['appsecret']){
				return false;
		}
		if($_SESSION['container']=='wxwork'){
			$url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=".$wechat['appid']."&corpsecret=".$wechat['appsecret'];
		}else{
			$url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$wechat['appid'].'&secret='.$wechat['appsecret'].'&code='.$code.'&grant_type=authorization_code';
		}
		$result=file_get_contents($url);
		if(!$result){
			$result=cfc('http')->ihttp_get($url);
			$result=$result['content'];
		}
		$result=json_decode($result,true);
		if($result['errcode']){
			return false;
			exit('获取openid失败：'.$result['errmsg']);
		}
		return $result;
	}
	//确认token是否有效
	public function check_token($access_token,$openid){
		$url='https://api.weixin.qq.com/sns/auth?access_token='.$access_token.'&openid='.$openid;
		$result=file_get_contents($url);
		if(!$result){
			$result=cfc('http')->ihttp_get($url);
			$result=$result['content'];
		}
		$result=json_decode($result,true);
		if($result['errcode']){
			return false;
		}
		return true;
	}
	public function refresh_token($wechat,$refresh_token){
		$url='https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$wechat['appid'].'&refresh_token='.$refresh_token.'&grant_type=efresh_token';
		$result=file_get_contents($url);
		if(!$result){
			$result=cfc('http')->ihttp_get($url);
			$result=$result['content'];
		}
		$result=json_decode($result,true);
		if($result['errcode']){
			return false;
			exit('获取openid失败：'.$result['errmsg']);
		}
		return $result;
	}
	public function get_userinfo($access_token,$openid,$code=''){
		if($_SESSION['container']=='wxwork'){
			$url='https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token='.$access_token.'&code='.$code;
		}else{
			$url='https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
		}
		$result=file_get_contents($url);
		if(!$result){
			$result=cfc('http')->ihttp_get($url);
			$result=$result['content'];
		}
		$result=preg_replace('/[\x00-\x1F]/','',$result);
		$result=preg_replace_callback('/[\xf0-\xf7].{3}/', function($r) { return '';}, $result);
		$result=@json_decode($result,true);
		if($result['errcode']){
			return false;
			exit('获取粉丝详情失败：'.$result['errmsg']);
		}
		if($_SESSION['container']=='wxwork'){
			$result['openid']=$result['OpenId']?:$result['UserId'];
		}
		return $result;
	}
	public function up_userinfo($op='base',$code=''){
		if($_SESSION['openid']){
			$files=array('id','mid','unionid','nickname','avatar','sex','tagid_list','pcd','expires_time','refresh_time','access_token','refresh_token');
			$fans=pdo_get('core_fans',array('openid'=>$_SESSION['openid'],'uniacid'=>$_SESSION['uniacid'],'wxgid'=>$_SESSION['wechat_id']),$files);
			$result['openid']=$_SESSION['openid'];
		}
		if($_SESSION['container']=='wxwork'){
			$wechat=pdo_get('core_account_wxwork',array('id'=>$_SESSION['wxwork_id']));
			$wechat['appsecret']=pdo_getcolumn('core_account_wxwork_app',array('id'=>$_SESSION['wxworkapp_id']),'appsecret');
		}else{
			$wechat=pdo_get('core_account_wechat',array('id'=>$_SESSION['wechat_id']));
			if($wechat['type'] !=4 && $_SESSION['auth_wxid']){
				$wechat=pdo_get('core_account_wechat',array('id'=>$_SESSION['auth_wxid']));
			}
		}
		if(!$wechat['appid'] || !$wechat['appsecret']){
			return false;
		}
		if($op=='info'){
			//获取详细信息,不缓存token
			if(!$code){
				return false;
			}
			$result=$this->get_access_token($wechat,$code);
			if(!$result['access_token']){
				return false;
			}
			if($_SESSION['container']!='wxwork'){
				$result=$this->get_userinfo($result['access_token'],$result['openid']);
			}
			$fansdata=array(
				'nickname'=>model('core/tools')->upnickname($result['nickname']),
				'avatar'=>$result['headimgurl'],
				'sex'=>$result['sex'],
				'tagid_list'=>$result['tagid_list']?';'.implode(';'.$result['tagid_list']).';':'',
				'pcd'=>$result['country'].$result['province'].$result['city'],
				'updatetime'=>TIMESTAMP,
			);
		}
		if($op=='base'){
			//刷新token
			if(TIMESTAMP>$fans['expires_time'] && $fans['refresh_time']>TIMESTAMP){	
					$result=$this->refresh_token($wechat,$fans['refresh_token']);
			}elseif($fans['access_token'] && $fans['expires_time']>TIMESTAMP){//2小时内,读取
					$result['access_token']=$fans['access_token'];
			}else{
					$result=$this->get_access_token($wechat,$code);
					$result['expires_in']=$result['expires_in']?:7200;
			}
			$access_token=$result['access_token']?:$fans['access_token'];
			$refresh_token=$result['refresh_token']?:$fans['refresh_token'];
			$expires_time=$result['expires_in']?$result['expires_in']+TIMESTAMP-200:$fans['expires_time'];
			$result['openid']=$result['openid']?:$_SESSION['openid'];
		}
		if($_SESSION['container']=='wxwork'){
			$result=$this->get_userinfo($result['access_token'],'',$code);
		}
		//再次判断openid
		if(!$result || !$result['openid']){
			return false;
		}
		$_SESSION['openid']=$result['openid'];
		if($result['unionid']){
			$_SESSION['unionid']=$result['unionid'];
		}
		$fans=pdo_get('core_fans',array('openid'=>$result['openid'],'uniacid'=>$_SESSION['uniacid'],'wxgid'=>$_SESSION['wechat_id']),array('id','mid','unionid','nickname','avatar','sex','tagid_list','pcd','expires_time','refresh_time','access_token','refresh_token'));
		if(!$fans['id']){
			//插入粉丝数据
			$insert=array(
				'uniacid'=>$_SESSION['uniacid'],
				'wxgid'=>$_SESSION['container']=='wxwork'?$_SESSION['wxwork_id']:$_SESSION['wechat_id'],
				'auth_wxid'=>$_SESSION['auth_wxid'],
				'type'=>$_SESSION['container']=='wxwork'?9:2,
				'mid'=>$_SESSION['uid']?:0,
				'unionid'=>$result['unionid'],
				'openid'=>$_SESSION['openid'],
				'isworkman'=>$result['UserId']?1:0,
				'createtime'=>TIMESTAMP,
				'access_token'=>$access_token,
				'refresh_token'=>$refresh_token,
				'expires_time'=>$expires_time,
				'refresh_time'=>TIMESTAMP+27*24*3600,
			);
			if($op=='info'){
				$insert=array_merge($fansdata,$insert);
			}
			//如果关联了
			if($result['unionid'] && !$_SESSION['uid']){
				$mid=pdo_getcolumn('core_members',array('uniacid'=>$_SESSION['uniacid'],'unionid'=>$result['unionid']),'id');
				if($mid){
					//登录会员
					model('core/member')->login($mid);
				}else if($op=='info' ){
					//获取到粉丝详情并注册会员
					$data=array_fields(array('nickname','avatar','sex','unionid','pcd'),$fansdata);
					$data['unionid']=$result['unionid'];
					$mid=model('core/member')->register($data);
				}
			}else if($op=='info' && !$_SESSION['uid']){
					$data=array_fields(array('nickname','avatar','sex','pcd'),$fansdata);
					$mid=model('core/member')->register($data);
			}
			if($mid){
				$insert['mid']=$mid;
			}
			pdo_insert('core_fans',$insert);
		}else{
			if($op=='info'){
				//判断是否获得粉丝数据：
				$update=array(
						'nickname'=>$fansdata['nickname']?:$fans['nickname'],
						'avatar'=>$fansdata['avatar']?:$fans['avatar'],
						'sex'=>$fansdata['sex']?:$fans['sex'],
						'tagid_list'=>$fansdata['tagid_list']?:$fans['tagid_list'],
						'pcd'=>$fansdata['pcd']?:$fans['pcd'],
						'updatetime'=>TIMESTAMP,
				);
				//没有绑定unionid时
				if($result['unionid'] && !$fans['unionid']){
					$update['unionid']=$result['unionid'];
				}
				pdo_update('core_fans',$update,array('id'=>$fans['id']));
				//如果已经登录的，就刷新数据
				if($_SESSION['uid']){
					$member=pdo_get('core_members',array('uniacid'=>$_SESSION['uniacid'],'id'=>$_SESSION['uid']),array('nickname','avatar','sex'));
					$member_update=array();
					if(!$member['nickname']){
						$member_update['nickname']=$fansdata['nickname']?:$fans['nickname'];
					}
					if(!$member['avatar']){
						$member_update['avatar']=$fansdata['avatar']?:$fans['avatar'];
					}
					if(!$member['sex']){
						$member_update['sex']=$fansdata['sex']?:$fans['sex'];
					}
					if($member_update){
						model('core/member')->member_update($_SESSION['uid'],$member_update);
					}
				}
			}else{
				//刷新token
				if(TIMESTAMP>$fans['expires_time'] && $fans['refresh_time']>TIMESTAMP){
					$update=array(
						'access_token'=>$access_token,
						'expires_time'=>$expires_time,
					);
					pdo_update('core_fans',$update,array('id'=>$fans['id']));
				}elseif(!$fans['access_token'] || $fans['refresh_time']<TIMESTAMP){
					$update=array(
						'access_token'=>$access_token,
						'refresh_token'=>$refresh_token,
						'expires_time'=>$expires_time,
						'refresh_time'=>TIMESTAMP+27*24*3600,
					);
					pdo_update('core_fans',$update,array('id'=>$fans['id']));
				}
				//没有绑定unionid时
				if($result['unionid'] && !$fans['unionid']){
					pdo_update('core_fans',array('unionid'=>$result['unionid']),array('id'=>$fans['id']));
				}
			}
			if($fans['mid'] || $fans['unionid']){
				//先判断是不是关联公众号
				if($fans['mid']){
						$member=pdo_get('core_members',array('id'=>$fans['mid'],'uniacid'=>$_SESSION['uniacid']),array('id','onemid'));
						$checkid=$member['onemid']>0?$member['onemid']:$member['id'];
				}
				if($fans['unionid'] && !$checkid){
						$member=pdo_get('core_members',array('unionid'=>$fans['unionid'],'uniacid'=>$_SESSION['uniacid']),array('id','onemid'));
						$checkid=$member['onemid']>0?$member['onemid']:$member['id'];
						pdo_update('core_fans',array('mid'=>$checkid),array('id'=>$fans['id']));
				}				
				if($checkid){
					model('core/member')->login($checkid);
				}else if($op=='info'){
					$indata=array_fields(array('nickname','avatar','sex','unionid','pcd'),$fansdata);
					$indata['unionid']=$result['unionid'];
					model('core/member')->register($indata);
				}else{
					model('core/member')->register();
				}
			}else{
				if($op=='info'){
					$indata=array_fields(array('nickname','avatar','sex','unionid','pcd'),$fansdata);
					$indata['unionid']=$result['unionid'];
					model('core/member')->register($indata);
				}else{
					model('core/member')->register();
				}
			}
		}
		return true;
	}
	public function up_openinfo($op='base',$code=''){
		//授权信息下根据code获取token
		if($_SESSION['openid']){
			$files=array('expires_time','refresh_time','access_token','refresh_token');
			$fans=pdo_get('core_open_user',array('open_uid'=>$_SESSION['openid']),$files);
			$result['openid']=$_SESSION['openid'];
		}
		$wechat=pdo_get('core_account_wechat',array('id'=>$_SESSION['wechat_id'],'uniacid'=>1));
		if(!$wechat['appid'] || !$wechat['appsecret']){
				return false;
		}
		if($op=='base'){
			//刷新token
			if(TIMESTAMP>$fans['expires_time'] && $fans['refresh_time']>TIMESTAMP){	
					$result=$this->refresh_token($wechat,$fans['refresh_token']);
			}elseif($fans['access_token'] && $fans['expires_time']>TIMESTAMP){//2小时内,读取
					$result['access_token']=$fans['access_token'];
			}else{
					$result=$this->get_access_token($wechat,$code);
					$result['expires_in']=$result['expires_in']?:7200;
			}
			$access_token=$result['access_token']?:$fans['access_token'];
			$refresh_token=$result['refresh_token']?:$fans['refresh_token'];
			$expires_time=$result['expires_in']?$result['expires_in']+TIMESTAMP-200:$fans['expires_time'];
			$result['openid']=$result['openid']?:$_SESSION['openid'];
		}else{
			if(!$code){
				return false;
			}
			$result=$this->get_access_token($wechat,$code);
			if(!$result['access_token']){
				return false;
			}
			$result=$this->get_userinfo($result['access_token'],$result['openid']);
			if($result['errcode']){
					return false;
			}
			$_SESSION['fans']=array(
					'nickname'=>model('core/tools')->upnickname($result['nickname']),
					'avatar'=>$result['headimgurl'],
					'sex'=>$result['sex'],
					'province'=>$result['province'],
					'city'=>$result['city'],
					'country'=>$result['country'],
			);
		}
		if(!$result['openid']){
			return false;
		}
		$_SESSION['openid']=$result['openid'];
		//登录/注册会员
		$files=array('open_uid','uniacid','expires_time','refresh_time','access_token','refresh_token');
		$fans=pdo_get('core_open_user',array('open_uid'=>$_SESSION['openid']),$files);
		$uniacid=$fans['uniacid'];
		if(!$uniacid){
			$zhuce=core_setting('zhuce');
			if($zhuce['open']){
					do{
						$username='wechat_'.random(10,true);
						$check=pdo_getcolumn('core_users',array('name'=>$username),'id');
					}while($check);
					$member=array('name'=>$username);
					$uniacid=cfc('user')->create_user($member);
					if($fans['open_uid']){
						pdo_update('core_open_user',array('uniacid'=>$uniacid),array('open_uid'=>$_SESSION['openid']));
					}else{
						$user=array(
							'uniacid'=>$uniacid,
							'open_id'=>'1003',
							'open_uid'=>$_SESSION['openid'],
							'wxgid'=>$_SESSION['wechat_id'],
							'access_token'=>$access_token,
							'refresh_token'=>$refresh_token,
							'expires_time'=>$expires_time,
							'refresh_time'=>TIMESTAMP+27*24*3600,
						);
						pdo_insert('core_open_user',$user);
					}
					if($_SESSION['islogout']!=1){
						cfc('user')->login($uniacid);
					}
			}
		}else{
			if($op=='base'){
				//刷新token
				if(TIMESTAMP>$fans['expires_time'] && $fans['refresh_time']>TIMESTAMP){
					$update=array(
						'access_token'=>$access_token,
						'expires_time'=>$expires_time,
					);
					pdo_update('core_open_user',$update,array('uniacid'=>$fans['uniacid']));
				}elseif($fans['uniacid'] && (!$fans['access_token'] || $fans['refresh_time']<TIMESTAMP)){
					$update=array(
						'access_token'=>$access_token,
						'refresh_token'=>$refresh_token,
						'expires_time'=>$expires_time,
						'refresh_time'=>TIMESTAMP+27*24*3600,
					);
					pdo_update('core_open_user',$update,array('uniacid'=>$fans['uniacid']));
				}
			}
			//登录时会判断刷新昵称等
			if($_SESSION['islogout']!=1){
				cfc('user')->login($uniacid);
			}
		}
	}
	//错误码
	public function error_code($code, $errmsg = '未知错误') {//获取错误详情
		global $_AR;
		$errors = array(
			'0'	=> '成功',
			'65400'	=> 'API不可用，即没有开通/升级到新版客服功能',
			'65401'	=> '无效客服帐号',
			'65402'	=> '帐号尚未绑定微信号，不能投入使用',
			'65403'	=> '客服昵称不合法',
			'65404'	=> '客服帐号不合法',
			'65405'	=> '帐号数目已达到上限，不能继续添加',
			'65406'	=> '已经存在的客服帐号',
			'65407'	=> '邀请对象已经是该公众号客服',
			'65408'	=> '本公众号已经有一个邀请给该微信',
			'65409'	=> '无效的微信号',
			'65410'	=> '邀请对象绑定公众号客服数达到上限（目前每个微信号可以绑定5个公众号客服帐号）',
			'65411'	=> '该帐号已经有一个等待确认的邀请，不能重复邀请',
			'65412'	=> '该帐号已经绑定微信号，不能进行邀请',
			'65413'	=> '不存在对应用户的会话信息',
			'65414'	=> '粉丝正在被其他客服接待',
			'65415'	=> '指定的客服不在线',
			'65416' => '查询参数不合法',
			'65417' => '查询时间段超出限制',
			'40001'	=> 'access_token获取失败',
			'40003'	=> '非法的openid',
			'40005'	=> '不支持的媒体类型',
			'40009'	=> '媒体文件长度不合法',
		);
		$code = strval($code);
		if($errors[$code]) {
			return $errors[$code];
		} else {
			$errmsg = $errmsg.',错误代码：'.$code;
			return $errmsg;
		}
	}
	
}